package org.way.message.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class MessageComponent {

    /**
     * 存储sessionId和webSocketSession
     * 需要注意的是，webSocketSession没有提供无参构造，不能进行序列化，也就不能通过redis存储
     * 在分布式系统中，要想别的办法实现webSocketSession共享
     */
    public static final Map<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();
    public static final Map<String, String> USER_MAP = new ConcurrentHashMap<>();

    public void sendMessage(String userId, String message) {
        String sessionId = USER_MAP.get(userId);
        WebSocketSession session = SESSION_MAP.get(sessionId);
        try {
            session.sendMessage(new TextMessage(message));
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }
}
